package com.taotao.designpattern.chain;


import java.util.LinkedList;

/**
 * 责任链上下文，用于传递公共信息
 *
 * @author fanbeibei
 * @version 1.0
 * @date 2021/1/5 10:43
 */
public class ChainContext {

    private Handler[] handlers;
    private int handlerIndex;

    public ChainContext(LinkedList<Handler> handlers0) {
        if (null != handlers0 || handlers0.size() > 0) {
            this.handlers = new Handler[handlers0.size()];
            handlers0.toArray(handlers);
        }
        this.handlerIndex = -1;
    }

    /**
     * 拉起下一个handler的HandleRequest方法
     *
     * @param request
     */
    public Response fireHandleRequest(Request request) {
        if (null == handlers || 0 == handlers.length) {
            return doWithNoHandler();
        }

        handlerIndex++;
        if (handlerIndex >= handlers.length) {
            return doWithNoHandler();
        }

        return handlers[handlerIndex].handleRequest(request, this);
    }

    private Response doWithNoHandler() {
        return null;
    }

}
